package com.example.wisdomclassroomapi.facade.filter;

import com.example.wisdomclassroomapi.common.cache.RedisCache;
import com.example.wisdomclassroomapi.common.dto.ResponseDto;
import com.example.wisdomclassroomapi.common.enums.ExceptionInfoEnum;
import com.example.wisdomclassroomapi.common.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache cache;

    private static final Set<String> ignoreUrl = new HashSet<>();

    static {
        ignoreUrl.add("/api/auth/captcha");
        ignoreUrl.add("/api/auth/register");
        ignoreUrl.add("/api/auth/login");
        ignoreUrl.add("/api/auth/reset/sendEmailCode");
        ignoreUrl.add("/api/auth/reset/checkEmailCode");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        // 匹配到忽略路径则放行
        if (ignoreUrl.contains(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        // 请求头无token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            response.getWriter().println(ResponseDto.fail(ExceptionInfoEnum.AM_USER_LOGIN_EXPIRE));
            return;
        }

        // 比较id是否一致
        String userId = JwtUtil.parse(token);
        Object cacheObject = cache.getCacheObject(userId);
        if (Objects.isNull(cacheObject)) throw new BadCredentialsException("token认证错误");

        // 设置SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication((Authentication) cacheObject);

        // 放行
        filterChain.doFilter(request, response);
    }
}
